//
//  ConsultViewController.m
//  drug
//
//  Created by 沈鑫 on 16/4/5.
//  Copyright © 2016年 沈鑫. All rights reserved.
//

#import "ConsultViewController.h"
#import "ConsultCollectionViewCell.h"
#import "RequestManager.h"
#import "ConsultModel.h"

#import "ConsultCollectionViewCellTwoCollectionViewCell.h"
#import "ConsultModel2.h"

#import "ConsultDetailViewController.h"
#import "ConsultDetailTwoViewController.m"

#import "MyTabBarViewController.h"


#import "MJRefresh.h"

#import "FMDB.h"
@interface ConsultViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate,UICollectionViewDelegateFlowLayout>



@property(nonatomic,strong)UIView *miniView;

@property(nonatomic,strong)UIView *hengView;



@property(nonatomic,strong)UIButton *yongButton;


@property(nonatomic,strong)UIButton *shouButton;



@property(nonatomic,strong)UIScrollView *scrollView;


@property(nonatomic,strong)UIView *myView;


@property(nonatomic,strong)UICollectionView *collectionView;

@property(nonatomic,strong)UICollectionView *collectionView2;

@property(nonatomic,strong)NSMutableArray *array1;

@property(nonatomic,strong)NSMutableArray *array2;


@property(nonatomic,assign)NSInteger startIndex;


@property(nonatomic,assign)NSInteger startIndex2;




@property(nonatomic,strong)FMDatabase *db1;

@property(nonatomic,strong)FMDatabase *db2;




@property(nonatomic,strong)UIImageView *imageView;




// 装数据库图片的数组
@property(nonatomic,strong)NSMutableArray *imageArray;





@property(nonatomic,strong)NSIndexPath *indexPath;



@end


@implementation ConsultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    // 数据持久化  新特药房
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)firstObject] stringByAppendingPathComponent:@"yybk1.db"];
    _db1 = [FMDatabase databaseWithPath:path];
    if (![_db1 open]) {
        NSLog(@"不能打开数据库");
    }
    
    // tableview表
    [_db1 executeUpdate:@"CREATE TABLE yybk11 (title text, addtime text,myId text,thumbnail text)"];
    
    
    // 数据持久化 保健养生

    NSString *path2 = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)firstObject] stringByAppendingPathComponent:@"yybk2.db"];
    _db2 = [FMDatabase databaseWithPath:path2];
    if (![_db2 open]) {
        NSLog(@"不能打开数据库");
    }
    
    // tableview表
    [_db2 executeUpdate:@"CREATE TABLE yybk22 (title text, addtime text,myId text,thumbnail text)"];
    
    

    
    
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"用药咨询";
    
    // navigation两边button 的颜色
   // [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    // navigation字体的颜色 大写 型号
    [self.navigationController.navigationBar setTitleTextAttributes: @{NSFontAttributeName: [UIFont fontWithName:@"Arial-BoldItalicMT" size:19],
                                                                       
                                                                       
                                                                       NSForegroundColorAttributeName:[UIColor whiteColor]}];
      self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.164 green:0.657 blue:0.915 alpha:1.000];
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 50, KWIDTH, KHEIGHT - 114)];
    _scrollView.contentSize = CGSizeMake(KWIDTH * 2, 0);
    _scrollView.contentOffset = CGPointMake(0, 0);
    _scrollView.delegate = self;
    _scrollView.pagingEnabled = YES;
    _scrollView.bounces = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_scrollView];
    
    
    // 第一个界面的collectionView
    UICollectionViewLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,0, KWIDTH, KHEIGHT - 114 - 44) collectionViewLayout:flowLayout];
    
    // 设置代理
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor blackColor];
    // 注册cell
    [_collectionView registerClass:[ConsultCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.scrollView addSubview:_collectionView];
    
    // 默认的下拉刷新方法
    
    _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        // 刷新的内容
        [self request1];
        
    }];

    // 默认的上拉刷新方法
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [self more];
    }];
    // 第二个界面的collectionView
    UICollectionViewLayout *flowLayout2 = [[UICollectionViewFlowLayout alloc]init];
    _collectionView2 = [[UICollectionView alloc]initWithFrame:CGRectMake(KWIDTH, 0, KWIDTH, KHEIGHT - 114 - 44)collectionViewLayout:flowLayout2];
    
    // 设置代理
    _collectionView2.delegate = self;
    _collectionView2.dataSource = self;
    _collectionView2.backgroundColor = [UIColor blackColor];
    // 注册cell
    [_collectionView2 registerClass:[ConsultCollectionViewCellTwoCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    

    
    [self.scrollView addSubview:_collectionView2];
    
    _miniView = [[UIView alloc]initWithFrame:CGRectMake(KWIDTH / 2, 0, 1, 40)];
    _miniView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_miniView];
    
    
    _hengView = [[UIView alloc]initWithFrame:CGRectMake(0, 40, KWIDTH, 1)];
    _hengView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_hengView];
    
    
    _yongButton  = [[UIButton alloc]initWithFrame:CGRectMake(0, 7, KWIDTH / 2, 30)];
    [_yongButton setTitle:@"新特药房" forState:UIControlStateNormal];
    [_yongButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    _yongButton.tag = 100;
    
    [_yongButton addTarget:self action:@selector(yongButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_yongButton];
    
    
    
    
    
    
    _shouButton = [[UIButton alloc]initWithFrame:CGRectMake(KWIDTH / 2, 7, KWIDTH / 2, 30)];
    [_shouButton setTitle:@"保健养生" forState:UIControlStateNormal];
    [_shouButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    _shouButton.tag = 200;
    [_shouButton addTarget:self action:@selector(shouButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_shouButton];
    
    
    [self request1];
    [self request2];
    
    
    
}








#pragma mark --- 网络请求 ---
-(void)request1
{
    
    _startIndex  = 0;
    [RequestManager requestWithUrl:@"http://apphy02.caeac.com.cn/500e32BD52027E652AA00003/androidapi/indexarticlec.php?w=1284&&n=20&p=0&t=36" requestType:RequestTypeGET parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        self.array1 = [ConsultModel getData:dic];
        
        // 先删除再添加
        [self deleteModel];
        
        
        [self addModel];
        
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.collectionView reloadData];
            
            [_collectionView.mj_header endRefreshing];
        });
        
        
        
    } error:^(NSError *error) {

        // 取出来的数据 赋值给 新的数组
        _array1 = [self getModel];
    
       
    
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.collectionView reloadData];
            
        });
    
    }];
    
    
    
}


-(void)request2
{
    
    _startIndex2 = 0;
    [RequestManager requestWithUrl:@"http://apphy02.caeac.com.cn/500e32BD52027E652AA00003/androidapi/indexarticlec.php?w=1284&&n=20&p=0&t=39" requestType:RequestTypeGET parDic:nil finish:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        self.array2 = [ConsultModel2 getData:dic];
        
        // 先删除再添加
        [self deleteModel1];
        [self addModel1];
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.collectionView2 reloadData];
            
            [_collectionView2.mj_header endRefreshing];
            
            
        });
        
    } error:^(NSError *error) {
        
       
        // 取出来的值给新的数组
        _array2 = [self getModel1];
    
   
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.collectionView reloadData];
            
        });
        
        
    }];
    
    
    
}




-(void)more
{
    
    
    _startIndex ++;
    if (_startIndex >= 3)
    {
        [_collectionView.mj_footer endRefreshing];
        
        return;
    }
    NSString *str = [NSString stringWithFormat:@"http://apphy02.caeac.com.cn/500e32BD52027E652AA00003/androidapi/indexarticlec.php?w=1284&&n=20&p=%ld&t=36",_startIndex];
    [RequestManager requestWithUrl:str requestType:RequestTypeGET parDic:nil finish:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSMutableArray *oneArray = [NSMutableArray array];
        
        
        oneArray = [ConsultModel getData:dic];
        
        for (NSMutableArray *aaArray in oneArray)
        {
            [_array1 addObject:aaArray];
        }
        
        
        
      
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.collectionView reloadData];
            
            [_collectionView.mj_footer endRefreshing];
            
        });
        
    } error:^(NSError *error) {
        
        NSLog(@"网络错误");
        
    }];
    
    
    
    
    
    
    
}








#pragma mark --- 返回行数 ---
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    if ([collectionView isEqual:_collectionView])
    {
        return _array1.count;
    }
    
    return _array2.count;
    
    
    
    
    
    
}

#pragma mark --- 返回cell ---
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (collectionView == _collectionView)
    {
        
        ConsultCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        
        ConsultModel *model = _array1[indexPath.row];
        
        [cell getData:model];
        
        return cell;
        
        
    }else
    {
        
        
        ConsultCollectionViewCellTwoCollectionViewCell *cell1 = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        
        
        ConsultModel2 *model1 = _array2[indexPath.row];
        
        
        
        [cell1 getData:model1];
        
        
        return cell1;
    }
    
}


#pragma mark --- 返回每个的高度和宽度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    //    if ([collectionView isEqual:_collectionView])
    //    {
    //        return CGSizeMake((KWIDTH  - 15)/ 2,(KWIDTH  - 15)/ 2);
    //    }
    NSLog(@"%f %f", KWIDTH , (KWIDTH - 15) / 2);
    return CGSizeMake((KWIDTH - 15) / 2 ,(KWIDTH - 15) / 2 );
    
}



#pragma mark --- 返回集合视图整体上 左 下 右编剧
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    //    if ([collectionView isEqual:_collectionView])
    //    {
    //        return UIEdgeInsetsMake(5, 5, 5, 5);
    //    }
    return UIEdgeInsetsMake(5, 2.5, 5, 2.5);
}



#pragma mark --- 控制集合视图的行边距 ---
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
//{
//    if ([collectionView isEqual:_collectionView])
//    {
//        return 10;
//    }
//    return 10;
//}




#pragma mark --- 控制集合视图的列边距 ---
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
//{
//    if ([collectionView isEqual:_collectionView])
//    {
//        return 10;
//    }
//    return 10;
//}



#pragma mark --- cell点击方法 ---


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    _indexPath = indexPath;
    if ([collectionView isEqual:_collectionView])
    {
       
        
        ConsultDetailViewController *consultDetail = [[ConsultDetailViewController alloc]init];
        ConsultModel *model = _array1[indexPath.row];
        consultDetail.myId = model.myId;
       consultDetail.hidesBottomBarWhenPushed = YES;
        
        
        [UIView animateWithDuration:1 animations:^{
            [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:YES];
        
        
      
        
        [self.navigationController pushViewController:consultDetail animated:YES];
        
        
        }];
    
    
        
        
        self.hidesBottomBarWhenPushed = NO;
        
    }else
    {
        

        ConsultDetailTwoViewController *consultDetail = [[ConsultDetailTwoViewController alloc]init];
        ConsultModel2 *model = _array2[indexPath.row];
        consultDetail.myId = model.myId;
        consultDetail.hidesBottomBarWhenPushed = YES;
        
        
        [UIView animateWithDuration:1 animations:^{
            [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:YES];
            
            
            
            
            [self.navigationController pushViewController:consultDetail animated:YES];
        }];
    }
}





#pragma mark --- 结束减速会触发的方法 ---
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    if (_scrollView.contentOffset.x == 0)
    {
        
        // [self request1];
        [_yongButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        [_shouButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        
        [UIView animateWithDuration:0.5 animations:^{
            
         
      _myView.frame = CGRectMake(58, 38, KWIDTH / 2 - 116, 2);
            
            
        }];
        
    }else
    {
        //   [self request2];
        [_shouButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        [_yongButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        
        [UIView animateWithDuration:0.5 animations:^{
            
            _myView.frame = CGRectMake(58 + KWIDTH / 2, 38, KWIDTH / 2 - 116, 2);
            
        }];
        
        
    }
    
    
    
    
    
}


-(void)yongButtonAction:(UIButton *)button
{
    [_yongButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [_shouButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    
    [UIView animateWithDuration:0.5 animations:^{
        _scrollView.contentOffset = CGPointMake(0, 0);
    }];
    
    [UIView animateWithDuration:0.5 animations:^{
        
        _myView.frame = CGRectMake(55, 38, 70, 2);
        
    }];
    
    
    
    
}


-(void)shouButtonAction:(UIButton *)button
{
    [_yongButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    
    [_shouButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    
    
    
    [UIView animateWithDuration:0.5 animations:^{
        _scrollView.contentOffset = CGPointMake(KWIDTH, 0);
        
    }];
    
    
    [UIView animateWithDuration:0.5 animations:^{
        
        _myView.frame = CGRectMake(245, 38, 70, 2);
        
    }];
    
    
    
}




#pragma mark --- 1插入数据 ---
- (void)addModel
{
    for (ConsultModel *model in _array1)
    {
        
        // integer类型 需要括号括起来
        [_db1 executeUpdate:@"INSERT INTO yybk11 (title, addtime,myId,thumbnail) VALUES (?, ? ,?, ?)",  model.title, model.addTime,model.myId,model.thumbnail];
    }
  
}




#pragma mark --- 2插入数据 ---
- (void)addModel1
{
    for (ConsultModel2 *model in _array2)
    {
        
        // integer类型 需要括号括起来
        [_db2 executeUpdate:@"INSERT INTO yybk22 (title, addtime,myId,thumbnail) VALUES (?, ? ,?, ?)",  model.title, model.addTime,model.myId,model.thumbnail];
    }
    
}






#pragma mark --- 1取出数据 ---
- (NSMutableArray *)getModel
{
    NSMutableArray *array = [NSMutableArray array];
    FMResultSet *result = [_db1 executeQuery:@"SELECT *FROM yybk11"];
    while ([result next])
    {
        ConsultModel *model = [[ConsultModel alloc]init];
        NSString *title = [result stringForColumn:@"title"];
        model.title = title;
        
        NSString *addTime = [result stringForColumn:@"addTime"];
        model.addTime = addTime;
        
        NSString *myId = [result stringForColumn:@"myId"];
        model.myId = myId;

        NSString *thumbnail = [result stringForColumn:@"thumbnail"];
        model.thumbnail = thumbnail;
        
        [array addObject:model];
    }
    [result close];
      NSLog(@"-----------%@",array);
    return array;
}



#pragma mark --- 2取出数据 ---
- (NSMutableArray *)getModel1
{
    NSMutableArray *array = [NSMutableArray array];
    FMResultSet *result = [_db2 executeQuery:@"SELECT *FROM yybk22"];
    while ([result next])
    {
        ConsultModel2 *model = [[ConsultModel2 alloc]init];
        NSString *title = [result stringForColumn:@"title"];
        model.title = title;
        
        NSString *addTime = [result stringForColumn:@"addTime"];
        model.addTime = addTime;
        
        NSString *myId = [result stringForColumn:@"myId"];
        model.myId = myId;
        
        NSString *thumbnail = [result stringForColumn:@"thumbnail"];
        model.thumbnail = thumbnail;
        
        [array addObject:model];
    }
    [result close];
    NSLog(@"-----------%@",array);
    return array;
}






#pragma mark --- 1删除数据 ---
- (void)deleteModel
{
    [_db1 executeUpdate:@"DELETE FROM yybk11"];
}


#pragma mark --- 2删除数据 ---
- (void)deleteModel1
{
    [_db2 executeUpdate:@"DELETE FROM yybk22"];
}


//放大的圈圈1
-(void)expandCoop1
{
    CGRect rect = CGRectInset(_imageView.frame, -700, -700);
    
    CGPathRef startPath = CGPathCreateWithEllipseInRect(rect, NULL);
    CGPathRef endPath   = CGPathCreateWithEllipseInRect(_imageView.frame, NULL);
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.path = startPath;
    
    self.view.layer.mask = maskLayer;
    
    CABasicAnimation *pingAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    
    pingAnimation.fromValue = (__bridge id)(endPath);
    pingAnimation.toValue   = (__bridge id)(startPath);
    pingAnimation.duration  = 1;
    pingAnimation.delegate = self;
    [pingAnimation setValue:@"animate1" forKey:@"animate1"];
    pingAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    
    [maskLayer addAnimation:pingAnimation forKey:@"pingInvert1"];
    
    CGPathRelease(startPath);
    CGPathRelease(endPath);
    
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(aaaaa:) userInfo:nil repeats:NO];
    
    
    
    
    
    
}

-(void)aaaaa:(NSTimer *)aa
{
    
    ConsultDetailViewController *consultDetail = [[ConsultDetailViewController alloc]init];
    ConsultModel *model = _array1[_indexPath.row];
    consultDetail.myId = model.myId;
    // 进行push 的时候 隐藏tabbar
    consultDetail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:consultDetail animated:YES];
    
    
}


//放大的圈圈2
-(void)expandCoop2
{
    CGRect rect = CGRectInset(_imageView.frame, -700, -700);
    
    CGPathRef startPath = CGPathCreateWithEllipseInRect(rect, NULL);
    CGPathRef endPath   = CGPathCreateWithEllipseInRect(_imageView.frame, NULL);
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.path = startPath;
    
    self.view.layer.mask = maskLayer;
    
    CABasicAnimation *pingAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    
    pingAnimation.fromValue = (__bridge id)(endPath);
    pingAnimation.toValue   = (__bridge id)(startPath);
    pingAnimation.duration  = 1;
    pingAnimation.delegate = self;
    [pingAnimation setValue:@"animate1" forKey:@"animate1"];
    pingAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    
    [maskLayer addAnimation:pingAnimation forKey:@"pingInvert1"];
    
    CGPathRelease(startPath);
    CGPathRelease(endPath);
    
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(aaaaaa:) userInfo:nil repeats:NO];
    
    
}

-(void)aaaaaa:(NSTimer *)aa
{
    
    ConsultDetailTwoViewController *twoDetail = [[ConsultDetailTwoViewController alloc]init];
    ConsultModel2 *model = _array2[_indexPath.row];
    twoDetail.myId = model.myId;
    twoDetail.hidesBottomBarWhenPushed = YES;
    
//    
//    [UIView animateWithDuration:1 animations:^{
//        [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:YES];
//        
        [self.navigationController pushViewController:twoDetail animated:YES];
    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end